//
//  CRTopicVideoView.m
//  CRChatRoom
//
//  Created by CuiFengshuai on 15/11/28.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRTopicVideoView.h"
#import "CRTopic.h"
#import "UIImageView+WebCache.h"
#import "CRPlayerManager.h"
@import AVFoundation;

@interface CRTopicVideoView ()

@property (weak, nonatomic) IBOutlet UILabel *playCountLabel;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *playButton;


@end

@implementation CRTopicVideoView


- (void)awakeFromNib {
    [super awakeFromNib];
    
    // 添加手势
    _imageView.userInteractionEnabled = YES;
    
    [_imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick)]];
    
}

- (void)setTopic:(CRTopic *)topic {
    [super setTopic:topic];
    
    [_imageView sd_setImageWithURL:[NSURL URLWithString:topic.large_image] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        topic.pictureProgress = 1.0;
    }];
    self.playCountLabel.text = [NSString stringWithFormat:@"%zd人播放", topic.playcount];
    self.timeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd", topic.videotime / 60, topic.videotime % 60];
    
    // 监听播放完成的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndPlay) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:AVPlayerItemDidPlayToEndTimeNotification];
    
}
- (IBAction)playButton:(UIButton *)button {
    // 隐藏播放按钮
    self.playButton.hidden = YES;

    CRPlayerManager *manager = [CRPlayerManager defaultManager];
    
    [manager playWithUrlStr:self.topic.videouri view:_imageView];
    
    [manager didToPlay];
    
}

- (void)didEndPlay {
    self.playButton.hidden = NO;
}

- (void)imageClick {
    [[CRPlayerManager defaultManager] didToStop];
    self.playButton.hidden = NO;
}


@end
